package com.hehe.controller;


import com.hehe.Dao.Test_Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Array;
import java.util.*;

@Controller
@RequestMapping(value="/sql")
public class Sql {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping(value="" )
    public String get_All(Model model,  String sql ){
        ArrayList<Object> arrayList = new ArrayList<>();
        if(sql == null || sql == ""){
            model.addAttribute("result_null" , -1 );
            model.addAttribute("column" , arrayList);
            model.addAttribute("sql" , "");
            return "select/sql.html";
        }
        ArrayList valuesList = new ArrayList();
        List<Map<String, Object>> results = jdbcTemplate.queryForList(sql);
        for(Map map : results){
            Collection values = map.values();
            System.out.println(values);
            valuesList.add(values);
        }

        if(results.size() == 0){
            model.addAttribute("result_null" , -1 );
            model.addAttribute("column" , arrayList);
            model.addAttribute("sql" , sql);
            return "select/sql.html";
        }

        model.addAttribute("results" , valuesList);
        model.addAttribute("column" , results.get(0).keySet());
        model.addAttribute("sql" , sql);
        return "select/sql.html";
    }




}




